<template>
  <div class="app-container">
    <!-- 添加导航栏 -->
    <div class="nav">
      <router-link to="/dashboard/dash" class="nav-link"><span>首页</span></router-link>
      <router-link :to="{ 
        name: 'project-manage', 
        params: { 
          param: staId,
          standardName: standardName 
        }
      }" class="nav-link">
        <span>/</span><span>{{ standardName }}</span>
      </router-link>
      <router-link :to="{
        name: 'project-manage',
        params: {
          param: staId,
          standardName: standardName,
          staName: standardName
        }
      }" class="nav-link">
        <span>/</span><span>{{ projectName }}</span>
      </router-link>
      <router-link :to="{
        name: 'moudle_select',
        params: {
          param: projectId,
          projectName: projectName,
          standardName: standardName,
          staId: staId
        }
      }" class="nav-link">
        <span>/</span><span>模块选择</span>
      </router-link>
      <span>/</span><span class="current-page">设备管理</span>
      <!-- 添加返回按钮 -->
      <div class="nav-back">
        <el-button type="text" @click="handleBack">
          <i class="el-icon-arrow-left"></i> 返回
        </el-button>
      </div>
    </div>

    <div class="standard-management-container">
      <div class="page-header">
        <div class="back-button-container">
          <button class="back-button" @click="handleBack()">
            <!-- <i class="el-icon-arrow-left"></i> -->
            <span>设备管理</span>
          </button>
        </div>
      </div>

      <div class="content-wrapper">
        <div class="search-and-buttons">
          <div class="search-box">
            <i class="el-icon-search search-icon"></i>
            <input
              type="text"
              class="search-input"
              placeholder="请输入搜索关键字"
              v-model="searchText"
            />
          </div>

          <div class="buttons">
            <el-button type="danger" icon="el-icon-delete" @click="deleteItems()">
              批量删除
            </el-button>
            <el-button type="primary" icon="el-icon-plus" @click="showDialog">
              添加设备
            </el-button>
            <el-button type="success" icon="el-icon-upload2" @click="triggerFileInput">
              导入Excel
            </el-button>
            <input
              type="file"
              ref="fileInput"
              @change="importFromExcel"
              style="display: none"
              accept=".xlsx, .xls"
            />
          </div>
        </div>

        <!-- 表格部分使用 el-table 替代原生 table -->
        <el-table
          :data="filteredItems"
          style="width: 100%"
          :header-cell-style="{ background: '#f5f7fa' }"
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column type="index" label="序号" width="80" align="center" />
          <el-table-column 
            prop="equipmentName" 
            label="设备名称" 
            align="center" 
            show-overflow-tooltip
          />
          <el-table-column 
            prop="unit" 
            label="单位" 
            width="120" 
            align="center" 
          />
          <el-table-column label="操作" width="200" align="center">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                @click="showItem(scope.row)"
                icon="el-icon-view"
              >
                查看
              </el-button>
              <el-button
                size="mini"
                type="danger"
                @click="deleteItem(scope.row)"
                icon="el-icon-delete"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 弹窗优化 -->
      <el-dialog 
        title="添加设备" 
        :visible.sync="dialogVisible"
        width="500px"
        :close-on-click-modal="false"
      >
        <el-form :model="form" label-position="right" label-width="100px" :rules="rules">
          <el-form-item label="设备名称" prop="deviceName">
            <el-input v-model="form.deviceName" placeholder="请输入设备名称"></el-input>
          </el-form-item>
          <el-form-item label="单位" prop="unit">
            <el-input v-model="form.unit" placeholder="请输入单位"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addProject">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import XLSX from "xlsx";

export default {
  name: "StandardManagement",
  data() {
    return {
      projectId: null,
      staId: null,
      standardName: '',
      projectName: '',
      items: [],
      searchText: "",
      dialogVisible: false,
      form: {
        deviceName: "",
        unit: "",
      },
      selectedItems: [],
      formLabelWidth: "120px",
    };
  },
  created() {
    // 优先使用路由参数，如果没有则使用localStorage中存储的值
    const { param, projectName, standardName, staId } = this.$route.params;
    
    this.projectId = param || localStorage.getItem('projectId');
    this.projectName = projectName || localStorage.getItem('projectName') || '未知项目';
    this.standardName = standardName || localStorage.getItem('standardName') || '未知标准';
    this.staId = staId || localStorage.getItem('staId');
    
    // 存储这些值到localStorage
    if (param) localStorage.setItem('projectId', param);
    if (projectName) localStorage.setItem('projectName', projectName);
    if (standardName) localStorage.setItem('standardName', standardName);
    if (staId) localStorage.setItem('staId', staId);

    if (this.projectId) {
      this.fetchItemsFromBackend();
    }
  },
  computed: {
    filteredItems() {
      if (!this.searchText) {
        return this.items;
      }
      return this.items.filter((item) => {
        return Object.values(item).some((value) =>
          value.toString().toLowerCase().includes(this.searchText.toLowerCase())
        );
      });
    },
  },
  methods: {
    // 在组件挂载时获取后端数据
    async fetchItemsFromBackend() {
      try {
        if (!this.projectId) {
          this.$message.error('项目ID不能为空');
          return;
        }

        // 使用 EquipmentList 接口获取设备列表
        const response = await this.$http.get("/EquipmentList", {
          params: { 
            pjId: this.projectId
          }
        });

        console.log('设备列表响应:', response.data); // 添加日志

        if (response.data && Array.isArray(response.data)) {
          // 添加数据格式检查和错误处理
          this.items = response.data.map(equipment => {
            if (!equipment) {
              console.warn('发现空的设备数据项');
              return null;
            }
            return {
              id: equipment.eId || '',
              equipmentName: equipment.eName || '',
              unit: equipment.eUnit || '台'
            };
          }).filter(item => item !== null); // 过滤掉无效的数据项
          
          if (this.items.length === 0) {
            this.$message.warning('暂无设备数据');
          }
        } else {
          console.warn('后端返回的数据格式不正确:', response.data);
          this.items = [];
          this.$message.warning('暂无设备数据');
        }
      } catch (error) {
        console.error("获取设备数据失败:", error);
        this.$message.error("获取设备数据失败: " + (error.message || '未知错误'));
        this.items = []; // 确保在错误时清空列表
      }
    },
    handleBack() {
      this.$router.push({
        name: 'moudle_select',
        params: {
          param: this.projectId,
          projectName: this.projectName,
          standardName: this.standardName,
          staId: this.staId
        },
        replace: true
      });
    },
    async deleteItems() {
      if (this.selectedItems.length === 0) {
        this.$message.warning('请先选择要删除的设备');
        return;
      }

      try {
        await this.$confirm('确认删除选中的设备吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });

        // 获取选中项的ID列表
        const eIds = this.selectedItems.map(item => item.id);
        console.log('准备删除的设备IDs:', eIds);

        // 使用正确的批量删除接口
        const response = await this.$http.delete('/deleteEquListOfProject', {
          data: eIds,  // 直接发送ID数组作为请求体
          headers: {
            'Content-Type': 'application/json'  // 确保设置正确的内容类型
          }
        });

        console.log('删除响应:', response);
        if (response.data === '删除成功') {  // 匹配后端返回的成功消息
          this.$message.success('批量删除成功');
          this.selectedItems = [];  // 清空选中项
          await this.fetchItemsFromBackend();  // 刷新数据
        } else {
          this.$message.error(response.data || '批量删除失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量删除失败:', error);
          this.$message.error('批量删除失败');
        }
      }
    },
    showDialog() {
      this.dialogVisible = true;
      this.form = {
        deviceName: '',
        unit: ''
      };
    },
    async addProject() {
      if (!this.form.deviceName || !this.form.unit) {
        this.$message.error('请填写完整息');
        return;
      }

      const payload = {
        pjId: this.projectId,
        eName: this.form.deviceName,
        eUnit: this.form.unit
      };

      try {
        const response = await this.$http.put('/addEquOfProject', payload);
        if (response.data === 1) {
          this.$message.success('添加设备成功');
          this.dialogVisible = false;
          this.form = { deviceName: '', unit: '' };
          await this.fetchItemsFromBackend();
        } else {
          this.$message.error('添加设备失败');
        }
      } catch (error) {
        console.error("添加设备失败:", error);
        this.$message.error("添加设备失败");
      }
    },
    triggerFileInput() {
      this.$refs.fileInput.value = null;
      this.$refs.fileInput.click();
    },
    importFromExcel(event) {
      const file = event.target.files[0];
      if (!file) {
        return;
      }
      const reader = new FileReader();
      reader.onload = (e) => {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: "array" });
        const sheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[sheetName];
        const json = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
        this.processImportedData(json);
      };
      reader.readAsArrayBuffer(file);
    },
    processImportedData(data) {
      if (data.length < 2) {
        this.$message.error('Excel文件内容为空');
        return;
      }
      try {
        const newItems = data.slice(1).map((row, index) => ({
          id: this.items.length + index + 1,
          equipmentName: row[0],
          unit: row[1]
        }));
        this.items = [...this.items, ...newItems];
        this.$message.success(`成功导入 ${newItems.length} 条数据`);
      } catch (error) {
        this.$message.error('导入失败，请检查Excel格式否正确');
      }
    },
    showItem(item) {
      this.$router.push({
        name: 'equip_plan',
        params: {
          id: item.id,
          param: this.projectId,
          projectName: this.projectName,
          standardName: this.standardName,
          staId: this.staId
        }
      });
    },
    async deleteItem(item) {
      try {
        await this.$confirm('确认删除该设备吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });

        const response = await this.$http.delete('/deleteEquOfProject', {
          params: { eid: item.id }
        });

        if (response.data === 1) {
          this.$message.success('删除成功');
          await this.fetchItemsFromBackend();
        } else {
          this.$message.error('删除失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error("删除失败:", error);
          this.$message.error("删除失败");
        }
      }
    },
    handleSelectionChange(selection) {
      // 直接保存选中的对象数组
      this.selectedItems = selection;
    }
  },
  async mounted() {
    // 组件挂载请求后端数据始化表格
    await this.fetchItemsFromBackend();
  },
};
</script>

<style scoped>
.standard-management-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.content-wrapper {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.back-button {
  display: flex;
  align-items: center;
  background: transparent;
  border: none;
  font-size: 18px;
  font-weight: 600;
  color: #333;
  cursor: pointer;
  padding: 0;
}

.back-button i {
  margin-right: 8px;
}

.search-and-buttons {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-box {
  position: relative;
  flex: 1;
  max-width: 400px;
}

.search-icon {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #909399;
}

.search-input {
  width: 100%;
  padding: 10px 15px 10px 35px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s;
}

.search-input:focus {
  border-color: #409eff;
  outline: none;
  box-shadow: 0 0 0 2px rgba(64,158,255,0.2);
}

.buttons {
  display: flex;
  gap: 12px;
}

/* 覆盖 element-ui 的一认样式 */
:deep(.el-table) {
  margin-top: 20px;
}

:deep(.el-table th) {
  background-color: #f5f7fa !important;
}

:deep(.el-button--mini) {
  padding: 7px 12px;
}

/* 导航栏样式 */
.nav {
  padding: 20px;
  background-color: #f5f7fa;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  margin-bottom: 20px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  position: relative;
}

.nav-link {
  text-decoration: none;
  color: #909399;  /* 非当前页面使用灰色 */
  font-size: 16px;
  transition: color 0.3s;  /* 添加颜色过渡效果 */
}

.nav-link:hover {
  color: #409EFF;  /* 鼠标悬停时变为蓝色 */
}

.nav span {
  color: #909399;  /* 分隔符使用灰色 */
  font-size: 16px;
  margin: 0 5px;
}

.current-page {
  color: #409EFF !important;  /* 当前页面使用蓝色 */
  font-weight: 500;  /* 当前页面加粗 */
}

.nav-back {
  position: absolute;
  right: 20px;
}

.nav-back .el-button {
  font-size: 14px;
  color: #909399;  /* 返回按钮使用灰色 */
}

.nav-back .el-button:hover {
  color: #409EFF;  /* 鼠标悬停时变为蓝色 */
}

.nav-back i {
  margin-right: 5px;
}
</style>
